package com.example.demo.service;


import com.example.demo.entity.Bill;
import com.example.demo.mapper.BillMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BillServiceImpl implements BillService {

    @Autowired
    BillMapper billMapper;

    @Autowired
    RedisTemplate redisTemplate;
//一切数据都是从缓存中redis里面取得
//  1，首先缓存里要有最新数据
// 2，如果缓存没有 从mapper里取得 放入缓存

    @Override
    public List<Bill> findBillsByWhere(Bill bill) {
        List<Bill> billList = (List<Bill>) redisTemplate.opsForValue().get("billList");
        if (billList == null) {
            List<Bill> bills = billMapper.findBillsByWhere(bill);
            redisTemplate.opsForValue().set("billList", bills, 1, TimeUnit.DAYS);
        }
        return (List<Bill>) redisTemplate.opsForValue().get("billList");

    }

    @Override
    public int insertBill(Bill bill) {
        int i = billMapper.insertBill(bill);
        if (i > 0) {
            List<Bill> bills = billMapper.findBillsByWhere(null);
            redisTemplate.opsForValue().set("billList", bills, 1, TimeUnit.DAYS);
        }
        return i;
    }

    @Override
    public Bill detailBill(Integer id) {
        Bill bill = (Bill) redisTemplate.opsForValue().get("bill" + id);
        if (bill == null) {
            redisTemplate.opsForValue().set("bill" + id, billMapper.detailBill(id));
        }
        return (Bill) redisTemplate.opsForValue().get("bill" + id);
    }

    @Override
    public int deleteBillById(Integer id) {

        int i = billMapper.deleteBillById(id);
        if (i > 0) {
            redisTemplate.delete("bill" + id);
            List<Bill> bills = billMapper.findBillsByWhere(null);
            redisTemplate.opsForValue().set("billList", bills, 1, TimeUnit.DAYS);
            i = 1;
        }
        return i;
    }


    /**
     * 利用缓存也是以数据库数据为准
     * 先修改数据库然后更新缓存
     *
     * @param bill
     * @return
     */
    @Override
    public int updateBill(Bill bill) {
        //redisTemplate.opsForValue().get("billList");
        int i = billMapper.updateBill(bill);
        if (i > 0) {
            redisTemplate.opsForValue().set("bill" + bill.getBillid(), bill);

            List<Bill> bills = billMapper.findBillsByWhere(null);
            redisTemplate.opsForValue().set("billList", bills, 1, TimeUnit.DAYS);
            i = 1;
        }
        return i;
    }
}
